<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 接口新增
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form ref="form" :model="form" label-width="110px" label-position="">
                 <el-form-item label="接口名称：">
                    <el-input v-model="form.name" placeholder="接口名称" style="width:500px"></el-input>
                </el-form-item>
                <el-form-item label="所属项目：" prop="project_id">
                    <el-select v-model="form.project_id" placeholder="选择项目" @change="getModuleByProject(form.project_id)" style="width:500px;">
                        <el-option v-for="project in projects"
                            :key="project.id"
                            :label="project.name"
                            :value="project.id"
                            >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属模块：" prop="modular">
                    <el-select v-model="form.module_id" placeholder="选择模块" style="width:500px">
                        <el-option v-for="time in modulars"
                            :key="time.id"
                            :label="time.name"
                            :value="time.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-divider></el-divider> -->
                <el-form-item label="请求方法：">
                    <el-select v-model="form.method" placeholder="请求方法">
                        <el-option
                            v-for="item in methodlist"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form :inline="true"  class="demo-form-inline">
                    <el-form-item label-width="110px" label="域名/IP：">
                        <el-input v-model="form.host" placeholder="如果填写则用该域名，否则使用运行时选择的域名" style="width:350px"></el-input>
                    </el-form-item>
                    <el-form-item  label-width="100px" label="端口号：">
                        <el-input v-model="form.port" placeholder="非必填" style="width:150px"></el-input>
                    </el-form-item>
                </el-form>
                <el-form-item label="接口路径：">
                    <el-input v-model="form.request.url" placeholder="例如： /project/names" style="width:500px"></el-input>
                </el-form-item>
                <el-tabs v-model="message">
                    <!-- 路径参数(Params) -->
                    <el-tab-pane :label="`路径参数(Params)`" name="first">
                        <el-form-item label="Params：">
                            <el-button type="primary" @click="addTableRow('apiParams')">添加params</el-button>
                            <base-input-table :tableData="form.request.apiParams" @removeRowByIndex="removeParamsByIndex" style="margin-top: 20px">
                            </base-input-table>
                        </el-form-item>
                        <el-form-item label="依赖Params：">
                            <el-button type="primary" @click="addTableRow('apiParamsPublic')">添加依赖params</el-button>
                            <base-input-table-public :tableData="form.request.apiParamsPublic" @removeRowByIndex="removeParamsPublicByIndex" style="margin-top: 20px">
                            </base-input-table-public>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 请求头(Haders) -->
                    <el-tab-pane :label="`请求头(Haders)`" name="second">
                        <el-form-item label="请求头：">
                            <el-button type="primary" @click="addTableRow('apiHeaders')">添加params</el-button>
                            <base-input-table :tableData="form.request.apiHeaders" @removeRowByIndex="removeHeadersByIndex" style="margin-top: 20px">
                            </base-input-table>
                        </el-form-item>
                        <el-form-item label="依赖请求头：">
                            <el-button type="primary" @click="addTableRow('apiHeadersPublic')">添加依赖params</el-button>
                            <base-input-table-public :tableData="form.request.apiHeadersPublic" @removeRowByIndex="removeHeadersPublicByIndex" style="margin-top: 20px">
                            </base-input-table-public>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 请求体(Body) -->
                    <el-tab-pane :label="`请求体(Body)`" name="third">
                        <el-form-item label="参数类型：">
                            <el-radio v-model="bodyType" label="1" @change="getValue()">JSON</el-radio>
                            <el-radio v-model="bodyType" label="2" @change="getValue()">from-data</el-radio>
                        </el-form-item>
                        <el-form-item v-if="bodyTypeShow" label="请求参数：">
                            <CodeEditor
                            :options="options"
                            :value="content"
                            @contentChange="contentChange"
                            style="height: 300px; width: 80%; margin-top:15px;"
                            >
                            </CodeEditor>
                        </el-form-item>
                        <el-form-item v-else label="请求参数：">
                            <el-button type="primary" @click="addTableRow('apiFormData')">添加 from-data</el-button>
                            <base-input-table :tableData="form.request.apiFormData" @removeRowByIndex="removeFormDataByIndex" style="margin-top: 20px">
                            </base-input-table>
                        </el-form-item>
                        <el-form-item label="依赖请求参数：">
                            <el-button type="primary" @click="addTableRow('apiBodyPublic')">添加依赖参数</el-button>
                            <base-input-table-public :tableData="form.request.apiBodyPublic" @removeRowByIndex="removeBodyPublicByIndex" style="margin-top: 20px">
                            </base-input-table-public>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 提取数据 & 断言 -->
                    <el-tab-pane :label="` 提取数据 & 断言 `" name="fourth">
                        <el-form-item label="提取数据：">
                            <el-button type="primary" @click="addTableRow('extract')">添加提取数据</el-button>
                            <a style="color: gray">（ 取到的数据会被放到每次执行产生的公共数据池，键值提取数据示例：data.list[0].name ）</a>
                            <base-input-table :tableData="form.request.extract" @removeRowByIndex="removeExtractByIndex" style="margin-top: 20px">
                            </base-input-table>
                        </el-form-item>
                        <el-form-item label="断言检查">
                            <el-button type="primary" @click="addTableRow('validate')">添加断言</el-button>
                            <base-validate-table :tableData="form.request.validate" @removeRowByIndex="removeValidateByIndex" style="margin-top: 20px">
                            </base-validate-table>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
                <el-form-item style="margin-top: 50px">
                    <el-button type="primary" @click="submitForm(form)">保存</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>

import baseValidateTable from '../SmallParts/baseValidateTable'
import baseInputTable from '../SmallParts/baseInputTable'
import baseInputTablePublic from '../SmallParts/baseInputTablePublic'
import CodeEditor from "../SmallParts/CodeEditor"
import {removeInArrayByIndex} from '../common/common'
import { projects_names } from '../../api/api';
import { project_in_modulars } from '../../api/api';
import { add_interface } from '../../api/api'

export default {
    name: 'apiadd',
    components: {   
                    baseValidateTable, 
                    baseInputTable, 
                    baseInputTablePublic, 
                    CodeEditor
                },
    data() {
        return {
            projects:[],
            modulars:[],
            form: {
                // 格式为: [{"keyName":"", "value":""}, {, , }...]
                name: null,
                project_id: null,
                module_id: null,
                request:{
                    method:"GET",
                    host: "",
                    port: "",
                    url: "",
                    apiParams: [],
                    apiParamsPublic: [],
                    apiHeaders: [
                        {"keyName":"Content-Type","value":"application/json"},
                        {"keyName":"User-Agent","value":"Mozilla/5.0 LiuXiang"},
                        {"keyName":"Authorization","value":"public"}
                    ],
                    apiHeadersPublic: [],
                    apiBodyType:2,
                    apiFormData: [],
                    apiBodyPublic: [],
                    apiBodyJson: {},
                    extract: [],
                    validate: [],
                }
            },
            methodlist: [{
                    value: 'GET',
                    label: 'GET'
                }, {
                    value: 'POST',
                    label: 'POST'
                }, {
                    value: 'PUT',
                    label: 'PUT'
                }, {
                    value: 'DELETE',
                    label: 'DELETE'
                },
                {
                    value: 'PATCH',
                    label: 'PATCH',
                }],
            bodyType: '2',
            bodyTypeShow: false,
            message: 'first',
            content:'',
            options: {
                language: "json",
                theme: 'vs-dark',
                readOnly: false
            },
        };
    },
    created() {
        this.getProjectList();
    },
    methods: {
        // 获取项目列表
        getProjectList() {
            projects_names(this.query)
            .then(response => {
                this.projects = response.data.data;
            }).catch(error => {
                console.log(error);
            });
        },
        // 获取某项目下的所有模块
        getModuleByProject(project_id){
            project_in_modulars(project_id)
            .then(response => {
                this.modulars = response.data.data;
            }).catch(error => {
                console.log(error);
            });
        },
        // 触发保存
        submitForm(form) {
            console.log(form);
            // console.log(JSON.stringify(form.request));
            add_interface(this.form)
            .then(response => {
                if (response.data.success == true){
                    this.$message.success(response.data.message);
                    // this.$router.push({
                    //     path: '/api',
                    // })
                }else {
                    this.$message.error(response.data.message);
                }
            })
            .catch(error => {
                this.$message.error(error);
            })
        },
        addTableRow(name){
                if(name === "apiHeaders"){
                    this.form.request.apiHeaders.push({});
                }
                else if (name === "apiHeadersPublic"){
                    this.form.request.apiHeadersPublic.push({});
                }
                else if (name === "apiParams"){
                    this.form.request.apiParams.push({});
                }
                else if (name === "apiParamsPublic"){
                    this.form.request.apiParamsPublic.push({});
                }
                else if (name === "apiFormData"){
                    this.form.request.apiFormData.push({});
                }
                else if (name === "apiBodyPublic"){
                    this.form.request.apiBodyPublic.push({});
                }
                else if (name === "extract"){
                    this.form.request.extract.push({});
                }
                else if (name === "validate"){
                    this.form.request.validate.push({});
                }
                else {
                    window.console.log("无法识别: " + name);
                }
        },
        // 移除params单行
        removeParamsByIndex(array, removeIndex){
            this.form.request.apiParams = removeInArrayByIndex(array, removeIndex);
        },
        // 移除params单行
        removeParamsPublicByIndex(array, removeIndex){
            this.form.request.apiParamsPublic = removeInArrayByIndex(array, removeIndex);
        },
         // 移除headers单行
        removeHeadersByIndex(array, removeIndex){
            this.form.request.apiHeaders = removeInArrayByIndex(array, removeIndex);
        },
        // 移除headers单行
        removeHeadersPublicByIndex(array, removeIndex){
            this.form.request.apiHeadersPublic = removeInArrayByIndex(array, removeIndex);
        },
        getValue(){
            if(this.bodyType == '1'){
                this.bodyTypeShow = true
                this.form.request.apiBodyType = 1
            }else{
                this.bodyTypeShow = false
                this.form.request.apiBodyType = 2
            }
        },
         // 移除FormDara单行
        removeFormDataByIndex(array, removeIndex){
            this.form.request.apiFormData = removeInArrayByIndex(array, removeIndex);
        },
        // 移除BodyPublic单行
        removeBodyPublicByIndex(array, removeIndex){
            this.form.request.apiBodyPublic = removeInArrayByIndex(array, removeIndex);
        },
        // 移除extract单行
        removeExtractByIndex(array, removeIndex){
            this.form.request.extract = removeInArrayByIndex(array, removeIndex);
        },
        // 移除validate单行
        removeValidateByIndex(array, removeIndex){
            this.form.request.validate = removeInArrayByIndex(array, removeIndex);
        },
        contentChange(value) {
            try {
                this.form.request.apiBodyJson = JSON.parse(value.replace(/\s*/g,""));
            }
            catch(err){
                // console.log(err)
            }
            
        },
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>


// npm uninstall